package com.wing.distribution.controller;

import com.alibaba.fastjson.JSONObject;
import com.wing.common.utils.JsonResult;
import com.wing.sms.feign.SmsClient;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserAuthVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Validated
@Api(value = "Admin-登录接口", tags = "#/login/admin")
@RestController("companyController")
@RequestMapping("login/admin/login")
public class LoginController {

    @Autowired
    private SmsClient smsClient;

    @Autowired
    private UserClient userClient;


    @ApiOperation(value = "发送手机验证码", notes = "发送手机验证码")
    @GetMapping("/sendSmsCode")
    public JsonResult sendSmsCode(@RequestParam("phone") String phone) {


        try{
            JsonResult<UserAuthVO> user = userClient.findUserByPhone(Long.valueOf(phone));
            if (Long.valueOf(user.getData().getUserId())==null){
                return JsonResult.fail("不是企业用户");
            }



            JsonResult result = smsClient.sendSmsCode(phone);

            if(null != result && result.getCode() == 200) {
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(result.getData()).toString());
                if (null != jsonObject && StringUtils.isNotBlank(jsonObject.getString("key"))) {
                    return JsonResult.success("发送成功！", jsonObject);
                }
            }
            if(null != result ){
                return JsonResult.fail("发送失败！" + result.getMsg());
            }else{
                return JsonResult.fail("发送失败！");
            }
        }catch(Exception e){
            log.error("发送短信失败：{}", e);
            return JsonResult.fail("发送失败！" + e);
        }
    }


}
